import React from 'react';
import PropTypes from 'prop-types';
import { Upload, Icon, Modal, message, notification } from 'antd';
import * as attachmentService from '../../services/attachment';

const { Dragger } = Upload;

var mimeMap = {
    "jpg": "image/jpeg",
    "png": "image/png",
    "jpeg": "image/jpeg",
    "doc": "application/msword",
    "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "pdf": "application/pdf",
}

export default class FileUpLoad extends React.Component {
    constructor(props) {
        super(props);
        const fileList = this.init(this.props.attIDs)
        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList: fileList,
            attIDs: this.props.attIDs
        };
    }
    componentWillReceiveProps(nextProps) {
        if (this.props.attIDs !== nextProps.attIDs) {
            const fileList = this.init(nextProps.attIDs)
            this.setState({ fileList })
        }
    }
    init(attIDs) {
        const fileList = attIDs.map((uid, i) => {
            return {
                uid: -uid,
                name: '附件' + i,
                status: 'done',
                url: `/api/attachment/file${i}/${uid}`,
            }
        })
        return fileList
    }
    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        if (file.response) {
            message.info("新添加的附件不支持下载！")
            return
        }
        const url = file.url || file.thumbUrl
        window.open(url, "blank")
    }
    getAttIds() {
        return this.state.attIDs
    }
    beforeUpload(file) {
        let flag = true
        const isType = file.type
        // if (isType !== mimeMap["doc"] && isType !== mimeMap["docx"] && isType !== mimeMap["pdf"] && isType !== mimeMap["jpg"] && isType !== mimeMap["png"] && isType !== mimeMap["jpeg"]) {
        //     notification.error({
        //         message: '上传失败  ',
        //         description:
        //             '不支持上传其他格式文件！,请在上传列表中删除后重新上传',
        //         icon: <Icon type="frown" style={{ color: 'red' }} />,
        //     });
        //     flag = false
        // }
        const size = file.size//1024*1024
        if (size > 2147483648) {
            notification.error({
                message: '上传失败  ',
                description:
                    '文件大小已超出最大值2GB，上传失败',
                icon: <Icon type="frown" style={{ color: 'red' }} />,
            });
            flag = false
        }
        return flag;
    }
    handleChange = ({ file, fileList }) => {
        if (file.status === 'done') {
            const attID = file.response
            let { attIDs } = this.state
            attIDs.push('' + attID)
            const len = fileList.length
            if (len > 0) {
                fileList[len - 1].url = `/api/attachment/${this.props.name}/${attID}`
            }
            this.setState({
                fileList: fileList.slice(-1),
                attIDs
            })
            notification.success({
                message: '上传成功',
                description:
                    '成功上传文件',
                icon: <Icon type="frown" style={{ color: '#108ee9' }} />,
            });
        }
        if (file.status === 'removed') {
            let attID = '' + file.response
            if (!attID) {
                attID = '' + -file.uid
            }
            let attIDs = this.state.attIDs
            if (attIDs.length > 0) {
                attachmentService.deleteAtt({ key: attIDs[0] })
            }
            const index = attIDs.indexOf(attID)
            attIDs.splice(index, 1);
            this.setState({
                fileList,
                attIDs
            })
        }
        if (file.status === 'error') {
            message.error(file.response.message)
        }
    }
    render() {
        let { name, disabled } = this.props
        const props2 = {
            disabled: disabled,
            name: name,
            multiple: false,
            showUploadList: true,
            action: `/api/attachment/${name}/0`,
            onChange: this.handleChange,
            onPreview: this.handlePreview,
            beforeUpload: this.beforeUpload,
        };
        return (
            <div>
                <Dragger {...props2} >
                    <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                    </p>
                    <p className="ant-upload-text">单击或拖动文件到此区域上传</p>
                    <p className="ant-upload-hint">
                        仅支持格式doc、docx、xlsx、xls、pdf、jpg、png、jpeg,<br />
                        上传不支持的格式会导致无法下载。上传错误文件时，请先删除，然后再上传。<br />
                        仅支持上传一个文件，若上传了多个文件，默认为第一个上传文件，文件大小上限为2GB。<br />
                    </p>
                </Dragger>
            </div >
        );
    }
}

FileUpLoad.propTypes = {
    name: PropTypes.string,
    attIDs: PropTypes.array,
    canEdit: PropTypes.bool,
    count: PropTypes.number,
    disabled: PropTypes.bool,

};
FileUpLoad.defaultProps = {
    name: "attachment",
    attIDs: [],
    canEdit: false,
    count: 1,
    disabled: false
};
